// 用户信息
var username = '';
var defaultName = "匿名小白";

window.onload = function () {
  var name_ = localStorage.getItem("userLoNmae") || defaultName;
  document.getElementById("userDIY").value = name_;
  document.getElementById("nowName").innerHTML = name_;
  document.getElementById("nowName2").innerHTML = name_;
  username = name_;

  document.getElementById('m').focus();
}

var socket = io('', {
  // Send auth token on connection, you will need to DI the Auth service above
  // 'query': 'token=' + Auth.getToken()
  path: '/socket.io',
  transports: ['websocket'],
  secure: true,
});

function getCurrentTime(time = null) {
  var date = new Date(time); //当前时间
  var month = zeroFill(date.getMonth() + 1); //月
  var day = zeroFill(date.getDate()); //日
  var hour = zeroFill(date.getHours()); //时
  var minute = zeroFill(date.getMinutes()); //分
  var second = zeroFill(date.getSeconds()); //秒
  //当前时间
  var curTime = "time: " + month + "-" + day +
    " " + hour + ":" + minute + ":" + second;
  return curTime;
}

/*
 * 补零
 */
function zeroFill(i) {
  if (i >= 0 && i <= 9) {
    return "0" + i;
  } else {
    return i;
  }
}


// 监听用户增减
socket.on('renshu', (renshu) => {
  // 添加一条系统消息
  document.getElementById("RS").innerText = "当前在线人数: " + renshu;
})

// 用户第一次链接请求，获取旧的数据
socket.on('init', (oldData) => {
  oldData.forEach(item => {
    if (item['msg'])
      addMessage(item)
    if (item['img'])
      addImg(item)
  })
})


// 发送事件
function SendM() {
  let m = document.getElementById("m");
  if (m.value != "") {
    socket.emit('sendMessage', {
      username: username,
      msg: m.value,
      time: new Date().getTime()
    });
    m.value = "";
  }
  document.getElementById('m').focus();
}

// 图片发送事件
document.getElementById("inputImg").onclick = function (e) {
  e.target.value = "";
}

function sendImg(input) {
  let file = input.files[0];
  let imgTs = document.getElementById("imgTs");
  // let size = file.size / 1024;
  // if (size < 750) {
  let reader = new FileReader();
  imgTs.style.visibility = "visible";
  imgTs.innerText = "读取中...";
  reader.readAsDataURL(file);
  // 读取完后，输出
  reader.onload = function () {
    imgTs.innerText = "尝试发送中...";
    socket.emit('sendimage', {
      username: username,
      img: reader.result,
      time: new Date().getTime()
    });
    imgTs.style.visibility = "hidden";
  }
  // } else {
  //   imgTs.innerText = "图片大于750kb，不予发送";
  //   imgTs.style.visibility = "visible";
  //   setTimeout(function () {
  //     imgTs.style.visibility = "hidden";
  //   }, 2600);
  // }
  input.value = "";
}


const messages = document.getElementById('messages');
// 捕获事件
socket.on('sendMessage', addMessage);
function addMessage(data) {
  let html = '';
  html = `<li class="${data.username == username ? 'mySelf' : 'qiTa'}">
    <h4>${data.username}</h4> <br>
    <pre onclick="copyText(this)">${to_link(data.msg)} </pre>
  </li>`
  messages.insertAdjacentHTML('beforeend', html);
  setTimeout(smoothscroll, 100);
}

// 捕获图片事件
socket.on('sendimage', addImg);
function addImg(data) {
  let html = '';
  html = `
  <li class="${data.username == username ? 'mySelf' : 'qiTa'}">
    <h4>${data.username}</h4><br />
    <img src="${data.img}" onclick="openYLK(this)" />
  </li>`
  messages.insertAdjacentHTML('beforeend', html);
  setTimeout(smoothscroll, 200);
}

function smoothscroll() {
  const currentScroll = messages.scrollTop; // 已经被卷掉的高度
  const clientHeight = messages.offsetHeight; // 容器高度
  const scrollHeight = messages.scrollHeight; // 内容总高度
  if (scrollHeight - 10 > currentScroll + clientHeight) {
    window.requestAnimationFrame(smoothscroll);
    messages.scrollTo(0, currentScroll + (scrollHeight - currentScroll - clientHeight) / 2);
  }
}


// 键盘事件绑定
document.onkeydown = function (event) {
  var e = event || window.event || arguments.callee.caller.arguments[0];
  if (e && e.ctrlKey && e.key === 'Enter') { // enter 键
    //要做的事情C
    SendM();
  } else if (e && e.keyCode == 113) {
    qKong();
  }
}

// 清空
function qKong() {
  document.getElementById('m').value = '';
  document.getElementById('m').focus();
}


// js 正则表达式来检查是否是链接
function to_link(txtContent) {
  var check_www = 'w{3}' + '[^\\s]*';
  var check_http = '(https|http|ftp|rtsp|mms)://' + '[^\\s]*';
  var strRegex = check_www + '|' + check_http;
  var httpReg = new RegExp(strRegex, 'gi');
  formatTxtContent = txtContent.replace(httpReg, function (httpText) {
    if (httpText.search('http') < 0 && httpText.search('HTTP') < 0) {
      return '<a href="' + 'http://' + httpText + '" target="_blank">' + httpText + '</a>';
    }
    else {
      return '<a href="' + httpText + '" target="_blank">' + httpText + '</a>';
    }
  });
  return formatTxtContent;
}

// 改名操作
function tbuName() {
  let name = document.getElementById("userDIY").value || defaultName;
  document.getElementById("nowName").innerText = name;
  document.getElementById("nowName2").innerText = name;
  username = name;
}
function okCOls() {
  document.getElementById("userData").style.top = "-100%";
  if (document.getElementById("loname").checked == true) {
    localStorage.setItem("userLoNmae", document.getElementById("userDIY").value);
  } else {
    localStorage.removeItem("userLoNmae");
  }
}
function okOpen() {
  document.getElementById("userData").style.top = "0";
  document.getElementById("userDIY").focus();
}